package com.bishi;

import java.rmi.registry.Registry;
import java.util.HashMap;
class RegSingleton{
    static private HashMap registry=new HashMap();
    //静态块，在类被加载时自动执行
    static{
        RegSingleton rs=new RegSingleton();
        registry.put(rs.getClass().getName(),rs);
    }
    //受保护的默认构造函数，如果为继承关系，则可以调用，克服了单例类不能为继承的缺点
    protected RegSingleton(){}
    //静态工厂方法，返回此类的唯一实例
    public static RegSingleton getInstance(String name){
        if(name==null){
            name="com.bishi.RegSingleton";
        }if(registry.get(name)==null){
            try{
                registry.put(name,Class.forName(name).newInstance());
            }catch(Exception ex){ex.printStackTrace();}
        }
        return (RegSingleton)registry.get(name);
    }
}

public class 单例注册表 {
    public static void main(String[] args) {
        RegSingleton regSingleton = new RegSingleton();
        RegSingleton regSingleton2 = new RegSingleton();
        System.out.println(regSingleton == regSingleton2);
        RegSingleton r1 = RegSingleton.getInstance(null);
        RegSingleton r2 = RegSingleton.getInstance(null);
        System.out.println(r1 == r2);
    }
}